package com.scau.hwadee.examination.realms;

import com.scau.hwadee.examination.entity.UserInfo;
import com.scau.hwadee.examination.mapper.UserInfoMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Auther: YHX
 * @Date: 2019/7/15 10:57
 * @Description: CREATED BY YHX
 */
public class ShiroRealm extends AuthenticatingRealm {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken uptoken = (UsernamePasswordToken) authenticationToken;
        UserInfo userInfo = userInfoMapper.getUserWithoutPassword(uptoken.getUsername());
        if (userInfo != null) {
            String userMessage = userInfo.getUserName()
                    + userInfo.getUserTelephone()
                    + userInfo.getUserEmail();
            Object principal =userInfo;
            Object hashedCredentials = userInfo.getUserPassword();
            ByteSource credentialsSalt = ByteSource.Util.bytes(userMessage);
            AuthenticationInfo info = new SimpleAuthenticationInfo(principal, hashedCredentials, credentialsSalt, getName());
            return info;
        } else {
            return null;
        }
    }

    @Test
    public void test(){
        String userMessage="xjl"+
                "32147896513"+
                "32147896513@abc.com";
        System.out.println((new SimpleHash("MD5","123456",userMessage,1024).toString()));
    }
}
